import { useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import { Button, Dialog, Form, Input, TextArea, Toast } from 'antd-mobile'
import PartyList from './components/partyList'
import Dictionary from '@src/assets/js/dictionary'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import Selector from '@components/selector'
import CardPicker from '@components/formCardPicker'
import style from './index.module.less'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { awaitWrap } from '@src/assets/js/tool'
import { pop } from '@src/redux/reducers/pages'
import PageLoading from '@components/pageLoading'
import { delRequest, getRequest, agentRequest } from './ajax'

const { Item, useForm } = Form

const keys = ['address', 'mobile', 'email', 'tel']

async function initData (id, formRef, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    initFormData(d, formRef)
    setData(d)
  }
}

function initFormData (d, formRef) {
  const keys = Object.keys(d)
  keys.forEach(k => {
    if (d[k] === null) {
      d[k] = undefined
    }
  })
  if (d.license_type) {
    d.license_type = [d.license_type]
  }
  if (d.file instanceof Array && d.file.length > 0) {
    d.front = d.file[0]
  }
  if (d.file1 instanceof Array && d.file1.length > 0) {
    d.back = d.file1[0]
  }
  formRef.setFieldsValue(d)
}

function formatSubmitData (d, caseid, isApply) {
  keys.map(k => {
    if (!d[k]) {
      d[k] = null
    }
  })
  d.caseid = caseid
  d.action_subject = isApply ? '申请人代理人' : '被申请人代理人'
  d.party_type = isApply ? '申请人' : '被申请人'
  d.license_type = d.license_type instanceof Array && d.license_type.length > 0 ? d.license_type[0] : undefined
  d.party.forEach(l => {
    delete l.upload
    delete l.file
    delete l.party
  })
}

async function submitHandle (d, caseid, isApply, dispatch) {
  formatSubmitData(d, caseid, isApply)
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(agentRequest(d))
  if (e === null) {
    dispatch(refreshCaseEditVersion())
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    setTimeout(() => {
      dispatch(pop())
    }, 500)
  }
}

async function delHandle (id, dispatch) {
  Toast.show({ content: '删除中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(delRequest(id))
  if (e === null) {
    dispatch(refreshCaseEditVersion())
    Toast.clear()
    Toast.show({ content: '删除成功', icon: 'success' })
    setTimeout(() => {
      dispatch(pop())
    }, 500)
  }
}

function Main ({ meta = { apply: false, id: '', caseid: '' } }) {
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const dispatch = useAppDispatch()
  const [data, setData] = useState(null)
  const [formRef] = useForm()
  const [options1, setOptions1] = useState([])
  const [loading, setLoading] = useState(false)
  const id = useMemo(() => {
    return meta && meta.id ? meta.id : ''
  }, [meta])
  const isEdit = useMemo(() => {
    return meta.id !== ''
  }, [meta])
  const isApply = useMemo(() => {
    return meta.apply
  }, [meta])
  const caseid = useMemo(() => {
    return meta && meta.caseid ? meta.caseid : ''
  }, [meta])
  const isMe = useMemo(() => {
    return !!data && userInfo.id === data.accountid
  }, [userInfo, data])
  const title = useMemo(() => {
    const l = []
    if (isEdit) {
      l.push('编辑')
    } else {
      l.push('添加')
    }
    if (isApply) {
      l.push('申请人代理人')
    } else {
      l.push('被申请人代理人')
    }
    return l.join('')
  }, [isEdit, isApply])
  useEffect(() => {
      const d = new Dictionary()
      d.init('自然人证件类型')
        .then(() => {
          setOptions1(d.getList('自然人证件类型').map(li => li.title))
        })
    }, [])
  useEffect(() => {
    if (id && formRef) {
      initData(id, formRef, setData, setLoading)
    }
  }, [id, formRef, isApply])
  if (loading) {
    return (
      <PageComponent title={title}><PageLoading /></PageComponent>
    )
  }
  return (
    <PageComponent title={title}>
      <Form layout='horizontal' form={formRef} onFinish={d => {
        Dialog.confirm({
          title: '您确定要提交吗？',
          onConfirm: () => {
            submitHandle(d, caseid, isApply, dispatch)
          }
        })
      }}>
        <Item name='id' noStyle><span /></Item>
        <Item name='party_type' noStyle><span /></Item>
        <Item label='代理对象' name='party' rules={[{ required: true, message: '代理对象不能为空' }]}>
          <PartyList caseid={caseid} apply={isApply} />
        </Item>
        <Item label='姓名' name='name' disabled={isMe} rules={[{ required: true, message: '代理人姓名不能为空' }]}>
          <Input placeholder='请输入' clearable />
        </Item>
        <Selector name='license_type' label='证件类型' disabled={isMe} rules={[{ required: true, message: '证件类型不能为空' }]} options={options1} formRef={formRef} />
        <Item name='license' label='证件号码' disabled={isMe} rules={[{ required: true, message: '证件号码不能为空' }]}>
          <Input placeholder='请输入' clearable />
        </Item>
        <Item label='证件照正面' name='front'>
          <CardPicker isFront />
        </Item>
        <Item label='证件照背面' name='back'>
          <CardPicker />
        </Item>
        <Item label='所在单位' name='structure' rules={[{ required: true, message: '所在单位不能为空' }]}>
          <Input placeholder='请输入' clearable />
        </Item>
        <Item name='address' label='地址' rules={[{ required: true, message: '地址不能为空' }]}>
          <TextArea placeholder='请输入' clearable autoSize={{ minRows: 3 }} />
        </Item>
        <Item name='mobile' label='手机号码'>
          <Input placeholder='请输入' clearable />
        </Item>
        <Item name='email' label='邮箱'>
          <Input placeholder='请输入' clearable />
        </Item>
        <Item name='tel' label='固定电话'>
          <Input placeholder='请输入' clearable />
        </Item>
        <Item>
          <div className={style.btns}>
            <Button type='submit' color='primary' block>提交</Button>
            {id && !isMe && <Button className={style.del} block onClick={() => {
              Dialog.confirm({
                title: '您确定要删除吗？',
                onConfirm: () => {
                  delHandle(id, dispatch)
                }
              })
            }}>删除</Button>}
          </div>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
